export const dataUrlToBlob = (dataUrl: string) => {
  const _array: any = dataUrl.split(',');
  const _mimeType = _array[0].match(/:(.*?);/)[1];
  const _bytes = window.atob(_array[1]);
  let _length = _bytes.length;
  const _uint8Array = new Uint8Array(_length);
  while (_length) {
    _length -= 1;
    _uint8Array[_length] = _bytes.charCodeAt(_length);
  }
  return new Blob([_uint8Array], { type: _mimeType });
};

export const dataUrlToBase64 = (dataUrl: string) => {
  const _array: any = dataUrl.split(',');
  const base64 = _array[1];
  return base64;
};

export const fileToDataUrl = (file: any, callback: any) => {
  const _fileReader = new FileReader();
  _fileReader.onload = (event) => {
    const __fileReader: any = event.target;
    callback(__fileReader.result);
  };
  _fileReader.readAsDataURL(file);
};

/**
 * 文件选择
 *
 * @param {function} complete 回调事件
 */
let element = null;
export const filePicker = (
  callback: any,
  option?: {
    accept?: string;
    capture?: string;
    multiple?: string;
  },
) => {
  element = document.createElement('input');
  element.setAttribute('type', 'file');
  const { accept = '*/*', capture, multiple } = option || {};
  element.setAttribute('accept', accept);
  if (capture) {
    element.setAttribute('capture', capture);
  }
  if (multiple) {
    element.setAttribute('multiple', 'multiple');
  }
  element.style.display = 'none';
  element.addEventListener(
    'change',
    (change_event: any) => {
      element = null;
      const _element: any = change_event.target;
      if (_element.value) {
        const { files } = _element;
        const fileObjs = [];
        for (let i = 0, { length } = files; i < length; i += 1) {
          const file = files[i];
          fileObjs.push({
            file,
          });
        }
        callback(fileObjs);
      }
    },
    true,
  );
  element.click();
};
